import { AppModel } from 'app/models/kdsConfig';
import { ConfigSvr } from './services/config';
import { TimeManager } from './utils/timeManager';
import { SolutionConfigService } from './components/solutionConfig';
import { ExitDialog, ExitDialogMessageResultType } from './components/exitDialog';
import { DeviceMessageHandle } from './utils/messageHandle/orderMessageHandle';
import { StoreSvr } from './services/store';
import { Devices } from './models/devices';
import { NodeService } from './services/system';
import { Order } from './models/order';
import { Observable } from 'rxjs/Observable';
import { AppStore, PagingInfo } from './services/appStore';
import { MessageHandleManager } from './utils/messageHandle/messageHandleManager';
import { FNCManager, KdsMessageType } from './utils/fnc/fncManager';
import { Authentication } from './services/authtication';
import { OrderSvr } from './services/order';
import { HostBinding } from "@angular/core";
import { Message, Header } from './components/common';
import { IMessageBoxContainer, MessageBoxService, MessageResult, GrowlMessageType, HandleExpectionErrorUseGrowMessage } from './components/messageBox';
import { NavigateService, ServiceBase } from "./services/index";
import { Router, ActivatedRoute } from '@angular/router';
import { formatTime } from "./utils/index";
import * as delay from 'delay';
import { MdDialogRef, MdDialog } from '@angular/material';

/*
 * Angular 2 decorators and services
 */
import { Component, ViewEncapsulation, ChangeDetectorRef } from '@angular/core';
import { AppState } from './services/app.service';

/*
 * App Component
 * Top Level Component
 */
@Component({
  selector: 'app',
  encapsulation: ViewEncapsulation.None,
  styleUrls: [
    './app.component.scss'
  ],
  template: `
    <mpj-growl [value]="GrowlMessage"></mpj-growl>
    <load-mask></load-mask>
    <print-container></print-container>
    <confirm [title]="Title" [content]="Content" [visible]="Visible" (onResult)="onResult($event)"></confirm>
  
    <md-sidenav-container class="container">
      <md-sidenav #sidenav class="sidenav">
          <ul>
              <li routerLink="/setup/order" (click)="sidenav.toggle()"><span class="nav-item"><i class="iconfont icon icon-setting"></i><span class="title">设置</span></span></li>
              <li (click)="toggleFullScrreen(sidenav)"><span class="nav-item"><i class="iconfont icon icon-full-screen"></i><span  class="title">{{window&&window.device&&window.device.isFullScreen()?"取消全屏":"全屏"}}</span></span></li>
              <li routerLink="/printer" (click)="sidenav.toggle()"><span class="nav-item"><i class="iconfont icon icon-help"></i><span  class="title">设备管理</span></span></li>
              <li (click)="sidenav.toggle()&&showKitchenSolutions()"><span class="nav-item"><i class="iconfont icon icon-merge"></i><span  class="title">合并显示</span></span></li>
              <li id="powerOffBtn" (click)="sidenav.close()&&powerOff()"><span class="nav-item"><i class="iconfont icon icon-power-settings-new"></i><span  class="title">关机</span></span></li>
          </ul>
      </md-sidenav>
      <div class="sidenav-content">
            <main>
                <router-outlet></router-outlet>
            </main>
            <nav class="" *ngIf="configSvr.appConfig.model==AppModel.FastFood">
                <button class="power" (click)="sidenav.toggle()">
                    <i class="material-icons">menu</i>
                </button>
                <span class="kdsname" (click)="showKitchenSolutions($event)">{{kitchenSolutionName}}<i class="triangle"></i></span>
                <span class="flex count-name">
                    {{currentTitle}} <span>{{(pagingInfo&&pagingInfo.orders.length) || 0}}</span> 单
                </span>
                <span class="time ">{{formatTime(time)}}</span>
                <button routerLink="/home" (click)="nav('待制作')" class="a layout-row layout-align-center-center" routerLinkActive="active">
                    <i class="iconfont  icon-assignment"></i>
                </button>
                <button routerLink="/finishedOrders"  (click)="nav('已完成')"  class="layout-row layout-align-center-center a" routerLinkActive="active">
                    <i class="iconfont  icon-assignment-turned-in"></i>
                </button>
                <button (click)="previous($event)" [class.zero]='((pagingInfo&&pagingInfo.count.previous) || 0)==0' class="layout-row layout-align-center-center paging">
                    <i class="iconfont icon-chevron-left"  ></i>
                    <span class="count"  >{{(pagingInfo&&pagingInfo.count.previous) || 0}}</span>
                </button>
                <button (click)="next($event)"  [class.zero]='((pagingInfo&&pagingInfo.count.next) || 0)==0' class="layout-row layout-align-center-center paging">
                    <span class="count" >{{(pagingInfo&&pagingInfo.count.next) || 0}}</span>
                    <i class="iconfont icon-chevron-right" ></i>
                </button>
            </nav>
            <nav class="" *ngIf="configSvr.appConfig.model==AppModel.HotPot">
                <button class="power" (click)="sidenav.toggle()">
                    <i class="material-icons">menu</i>
                </button>
                <span class="kdsname" (click)="showKitchenSolutions($event)">{{kitchenSolutionName}}<i class="triangle"></i></span>
                <span class="flex count-name">
                    {{currentTitle}}
                    <span>{{(pagingInfo&&pagingInfo.count.next) || 0}}菜</span> 
                    /
                    <span>{{(pagingInfo&&pagingInfo.count.previous) || 0}}单</span> 
                </span>
                <span class="time ">{{formatTime(time)}}</span>
                <button routerLink="/newHome" (click)="nav('待出品')" class="wh layout-row layout-align-center-center" routerLinkActive="active">
                    待出品
                </button>
                <button routerLink="/newFinishedOrders" class="wh layout-row layout-align-center-center" routerLinkActive="active">
                    已完成
                </button>
            </nav>
            <div *ngIf="currentDevice&&currentDevice.transferOut" class="fix-all" style="background: black;z-index: 200;">
                <p style="color:white;text-align: center;margin-top: 15rem;">此终端已经转移到{{currentDevice.name}}({{currentDevice.transferOutDevcie&&currentDevice.transferOutDevcie.kitchenSolution&&currentDevice.transferOutDevcie.kitchenSolution.name}})上显示</p>
                <p style="text-align: center;margin-top: 24px;"><button style="border-radius: 5px;color:black;background:white;padding: 8px 48px;font-size: 1rem;" (click)="canceltTransferOut(currentDevice.id, currentDevice.transferOut)">取消</button></p>
            </div>
            <div *ngIf="isWarningHidden&&failNodeService" class="app-warning"> 
                <i class="iconfont icon-warning"></i>
                <span>本地数据中心连接失败！请检测收银终端（{{LDCConfig&&(LDCConfig.sets+"-"+(LDCConfig.value.terminal&&LDCConfig.value.terminal.name))}},{{LDCConfig&&LDCConfig.ip}}）是否开机，网络是否正常。</span>
                <i class="iconfont icon-clear" (click)="setWarningHidden()"></i>
            </div>
            <solution-config></solution-config>
            <play-audio></play-audio>
      </div>
    </md-sidenav-container>
  `,
  providers: [MessageBoxService, NavigateService, ServiceBase, Authentication]
})
export class AppComponent implements IMessageBoxContainer {
  Title: string;
  Content: string;
  Visible: boolean;
  showOK: boolean = true;
  showCancel: boolean = true;
  showIgnore: boolean = false;
  GrowlMessage: Message[];
  isOnLoading: boolean = false;
  onResult;
  time = TimeManager.current.getServerTime();
  isDarkTheme: boolean = false;
  @HostBinding('class.layout-column') layoutColoum: boolean = true;
  constructor(
    private navSvr: NavigateService,
    private router: Router,
    private route: ActivatedRoute,
    private svr: ServiceBase,
    private orderSvr: OrderSvr,
    public appStore: AppStore,
    public changeDetectorRef: ChangeDetectorRef,
    private storeSvr: StoreSvr,
    public dialog: MdDialog,
    private configSvr: ConfigSvr
  ) {
    window["router"] = router;
    MessageBoxService.current.Regist(this)
    navSvr.registRouter(router);
    navSvr.AuthCheck(window.location.href);
    this.init();
  }
  AppModel = AppModel
  private isWarningHidden: Boolean = true;
  public failNodeService: NodeService;
  private pagingInfoObservable: Observable<PagingInfo>;
  private pagingInfo: PagingInfo;
  private kitchenSolution: any;
  private currentTitle = "待制作";
  private LDCConfig;
  private kitchenSolutionName: String;

  private currentDevice;
  async canceltTransferOut(currentDeviceId, transferOut) {
    const device = await this.storeSvr.cancelTransferDevice(currentDeviceId, transferOut);
    FNCManager.Current.KdsMessageNotify(KdsMessageType.DeviceMessage, device);
    this.storeSvr.currentDevice = device;
    this.refreshCurrentDevice();
  }
  @HandleExpectionErrorUseGrowMessage()
  async refreshCurrentDevice() {
    this.storeSvr.currentDevice = await this.storeSvr.getDeviceById(this.storeSvr.getCurrentDeviceId());
    this.currentDevice = this.storeSvr.currentDevice;
    if (this.currentDevice && this.currentDevice.transferOut) {
      this.currentDevice.transferOutDevcie = await this.storeSvr.getDeviceById(this.currentDevice.transferOut)
    }
  }

  async powerOff() {
    if (this.storeSvr.currentDevice) {
      let dialogRef = this.dialog.open(ExitDialog);
    } else {
      (<any>window).device.exitApp();
    }
  }
  private formatTime(time) {
    const dateTime = new Date(time);
    const hour = dateTime.getHours();
    const minutes = dateTime.getMinutes();
    const _time = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09"]
    return (_time[hour % 12] || hour % 12) + " : " + (_time[minutes] || minutes) + (hour / 12 > 1 ? "  下午 " : "  上午 ");
  }
  private async init() {
    setTimeout(() =>{
      if (this.navSvr.currentKitchenSolutions) {
        this.navSvr.navigate(["initialization/checkOldEnv"]);
      } else {
        this.navSvr.navigate(["initialization/welcome"]);
      }
    }, 0);


    // this.navSvr.navigate(["home"]);
  }
  private setWarningHidden() {
    this.isWarningHidden = false;
  }
  private async kdsHelp(sidenav) {
    sidenav.toggle();
    await delay(200);
    //打开帮助网页
    const url = "https://www.menpuji.com/";
    if (/windows|win32/i.test(navigator.userAgent)) {
      window.open(url, '_blank');
    } else {
      (<any>window).device.openSystemBrowser(url);
    }
  }
  private async toggleFullScrreen(sidenav) {
    sidenav.toggle();
    await delay(200);
    (<any>window).device.fullScreen(!(<any>window).device.isFullScreen());
  }
  async ngOnInit() {
    //设置模式
    try {
      this.refreshCurrentDevice();
    } catch (error) {

    }

    //设置 html/font-size
    // (<any>document.firstElementChild).style.fontSize = "10px";
    //注册窗口的退出事件
    (<any>window).device && (<any>window).device.onExitApp(function () {
      document.getElementById("powerOffBtn").click();
    })
    //不应该放在这里了
    this.pagingInfoObservable = this.appStore.gloablStore.pagingInfoObservable;
    this.pagingInfoObservable.subscribe(pagingInfo => {
      const appModel = this.configSvr.appConfig.model;
      if (appModel == this.AppModel.HotPot) { //快餐就计算订单总量和多少个菜
        const orders = pagingInfo.orders;
        const allOrdersCount = orders.map(order => {
          return order.items.filter(item => !item.deliverTime).map(x => x.qty - (x.refundQty || 0)).reduce((x, y) => x + y, 0)
        }).reduce((x, y) => x + y, 0);
        pagingInfo.count = {
          previous: orders.length,
          next: allOrdersCount
        }
      }
      this.pagingInfo = pagingInfo;
      // debugger
    })
    if (!this.LDCConfig) {
      this.LDCConfig = this.svr.LDCConfig;
    }

    Observable.interval(60000).subscribe(x => {
      this.time = TimeManager.current.getServerTime();
    })
  }
  private nav(link) {
    this.currentTitle = link;
  }

  private previous(event) {
    this.pagingInfo.actions.previousPage();
  }
  private next(event) {
    this.pagingInfo.actions.nextPage();
  }
  private async showKitchenSolutions(event) {
    SolutionConfigService.current.open();
  }
  async refreshKitchenSolutionName() {
    this.kitchenSolutionName = await SolutionConfigService.current.getCurrentKitchensolutionNames();
  }
  async ngAfterViewInit() {
    SolutionConfigService.current.onResult = result => {
      this.kitchenSolutionName = result.kitchenSolutionName;
    }
    const deviceMessageHandle = MessageHandleManager.Current.GetMessageHanle<DeviceMessageHandle>("DeviceMessageHandle");
    deviceMessageHandle.OnMessage = async (device) => {
      try {
        await this.refreshCurrentDevice();
        this.kitchenSolutionName = await SolutionConfigService.current.getCurrentKitchensolutionNames()
        this.appStore.orderStore.actions.resetAllOrders();
      }
      catch (error) {
        MessageBoxService.current.Growl(GrowlMessageType.Error, "错误提示", error.message || error);
      }
    }
  }

}
